<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2017 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://think.ctolog.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\store\service;

class ExcelService
{
    private $objPHPExcel = null;
    private $cellName = [];

    public function __construct()
    {
        $this->objPHPExcel = new \PHPExcel();
        $a = range('A', 'Z');
        $this->cellName = $a;
        foreach ($a as $s) {
            foreach ($a as $e) {
                $this->cellName[] = $s . $e;
            }
        }
    }

    // 导出excel
    public function export($title, $cell, $data)
    {
        // $cellTitle = iconv('utf-8', 'gb2312', $title);
        $cellNum = count($cell);
        $dataNum = count($data);
        $this->objPHPExcel->getActiveSheet(0)->mergeCells('A1:' . $this->cellName[$cellNum - 1] . '1');
        $this->objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $title . ' Export time:' . date("Y-m-d H:i:s"));
        for ($i = 0; $i < $cellNum; $i++) {
            $this->objPHPExcel->setActiveSheetIndex(0)->setCellValue($this->cellName[$i] . '2', $cell[$i][1]);
        }
        for ($i = 0; $i < $dataNum; $i++) {
            for ($j = 0; $j < $cellNum; $j++) {
                $this->objPHPExcel->getActiveSheet(0)->setCellValueExplicit($this->cellName[$j] . ($i + 3), $data[$i][$cell[$j][0]], \PHPExcel_Cell_DataType::TYPE_STRING);
            }
        }
        $fileName = date("Y-m-d-His");
        header('pragma:public');
        header('Content-type:application/vnd.ms-excel;charset=utf-8;name="' . $title . '.xls"');
        header("Content-Disposition:attachment;filename=$fileName.xls");
        $objWriter = \PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }


    public function import($file, $type = 'Excel5')
    {
        $objReader = \PHPExcel_IOFactory::createReader($type);
        $objExcel = $objReader->load($file);
        $sheet = $objExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        $data = [];
        for($j=2;$j<=$highestRow;$j++) {
            for($k='A';$k<=$highestColumn;$k++) {
                $data[$j][] = $objExcel->getActiveSheet()->getCell("$k$j")->getValue();
            }
        }
        return $data;
    }
}